import {
    SET_USER_INFO
} from '../mutation-types';
import api from '../../api';


const state = {
    nickname: null,
    age: null,
    sex: null,
    height: null,
    weight: null,
    phone: null,
    avatar: null,
    kcal: null,
    time: null,
    id: null,
    subscribe: false
}

// 格式化分钟
function time(time) {
    if (time <= 60) {
        return time
    } else if (time < 3600 && time > 60) {
        var mins = parseInt(time / 60);
        return mins
    } else {
        var hours = parseInt(time / 3600);
        return hours;
    }

}

// 获取url的参数
function queryUrlParamByName(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

const mutations = {
    [SET_USER_INFO](state, data) {
        // console.log(data);
        state.nickname = data.user.nickname;
        state.age = data.user.age;
        state.sex = data.user.sex;
        state.height = data.user.height;
        state.weight = data.user.weight;
        state.avatar = data.user.avatar;
        state.id = data.user.id;
        state.parts = data.user.parts;
        state.phone = data.user.phone;
        state.time = data.total.time;
        state.times = time(data.total.time);
        state.kcal = data.total.kcal.toFixed(1);
        state.couponNum = data.couponNum;
        state.subscribe = data.user.subscribe;
    }
}

// ACTION
const actions = {
    GET_USER_INFO: ({
        commit,
        dispatch
    }, id) => {
        api.getUserInfo().then(response => {
                //   console.log(response.data.total.time);
                // 当TOKEN手动被清除的时候
                // if (response.status != 200) {
                //     // todo 缺少提示
                //     var id = window.localStorage.getItem('id');
                //     var enterpriseID = window.localStorage.getItem('enterpriseID')
                //     if (id != null || id != '' || id != 'null' || enterpriseID != null || enterpriseID != '' || enterpriseID != 'null') {
                //         window.localStorage.removeItem('token');
                //         var replaceUrl = "http://wechat.shapejoy.com/unity/" + id + "/login?enterpriseID" + enterpriseID;
                //         window.location.replace(replaceUrl);
                //         return;
                //     }
                // } else {
                commit(SET_USER_INFO, response.data);
                // }
            })
            // )
    }
}

export default {
    state,
    actions,
    mutations
}